from mydefine import *

def login(head_recved, db):
    block_size = head_recved['block_size']
    if 0 == len(block_size):
        head_tosend = {"type": RESPONSE_ERROR, "status": "没有数据！"}
    name_in = head_recved['name']
    pswd_in = head_recved['pswd']

    status,users = db.sqlexe(f'select id,name,password,permission from tb_user where name=="{name_in}"')
    if None != status:
        return {"type": RESPONSE_ERROR, "status": status}
    if len(users)==0:
        return {"type": RESPONSE_LOGIN, "status": "用户不存在"}
    
    (id, name, pswd, permission) = users[0]

    if pswd_in != pswd:
        return {"type": RESPONSE_LOGIN, "status": "密码错误"}

    print(f'login: id="{id}", name="{name}", pswd="{pswd}", permission="{getUserPermission(permission)}"')
    
    head_tosend = {
        "type": RESPONSE_LOGIN,
        "status": "",
        "models": {},
        "name": name,
        "permission": permission,
    }
    return head_tosend

# 客户端只能注册普通权限用户
def signup(head_recved, db):
    block_size = head_recved['block_size']
    if 0 == len(block_size):
        head_tosend = {"type": RESPONSE_ERROR, "status": "没有数据！"}
    name_in = head_recved['name']
    pswd_in = head_recved['pswd']

    status,users = db.sqlexe(f'select * from tb_user where name=="{name_in}"')
    if None != status:
        return {"type": RESPONSE_ERROR, "status": status}
    if len(users) > 0:
        print("用户名重复")
        return {"type": RESPONSE_SIGNUP, "status": "用户名重复"}

    status,_ = db.sqlexe(f'insert into tb_user (name,password,permission) values ("{name_in}","{pswd_in}","{UP_NORMAL}")')
    if None != status:
        return {"type": RESPONSE_ERROR, "status": status}
    
    print(f'signup: name="{name_in}", pswd="{pswd_in}", permission="{getUserPermission(UP_NORMAL)}"')
    
    head_tosend = {
        "type": RESPONSE_SIGNUP,
        "status": "",
        "models": {},
        "name": name_in,
        "permission": UP_NORMAL,
    }

    return head_tosend
